home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 950 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  79 lines

  1. Path: howland.reston.ans.net!gatech!clientlink!usenet
  2. From: Matthew Raffel <raffelm@netcom.com>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: allocating unlimited string input....HELP
  5. Date: 10 Jan 1996 13:13:48 GMT
  6. Organization: ClientLink Corp.
  7. Message-ID: <4d0e2c$4uq@clientlink.com>
  8. NNTP-Posting-Host: 199.250.228.30
  9.  
  10. ryangall@gpu.srv.ualberta.ca (Bobby Sixkiller) writes:
  11.  
  12. A few things I may consider note worthy:
  13.  
  14. You need test B for a vailidity as a pointer.
  15. EG: 
  16. if (!B) 
  17.    printf("\nMalloc Failed");
  18.  
  19. Additionally, you are never freeing B before "realloc"ing
  20. it.  What is happening here, B gets set to point to
  21. some hunk of memory, then gets pointed to another hunk
  22. and another and so on.  The pieces of memory B pointed to
  23. a one point is never released back to the system.  This could
  24. be the cause of the failure after a fixed point, especially
  25. if you are compiling in a small or compact memory model.
  26.  
  27. You can avoid "needing" A by using realloc which 
  28. will preserve the contents of the memory.
  29.  
  30. Below is a "rewrite" of your code to implement my thoughts.
  31. One, note, I did not compile it so...look out :=)
  32.  
  33.  int read(char *S)
  34.  {
  35.   char *B = NULL;
  36.   char ch,count=0;
  37.   int  iCounter = 0;
  38.  
  39.  
  40.    /* create an initial size */
  41.    B = malloc(6);
  42.  
  43.    ch=getc(stdin);
  44.  
  45.    while(ch!='\n')
  46.    {
  47.      /* only realloc every so often...increment memory size by 5 bytes each time
  48.      if (iCount == 5)
  49.      {
  50.        B=(char *) relloc(B, count + 5);
  51.        iCount = 0;
  52.      }
  53.      else
  54.        iCount ++;
  55.      
  56.      if (!b)
  57.      {
  58.        printf("\nB does not exist");
  59.        break;
  60.      } 
  61.      else
  62.      {
  63.        sprintf(B,"%s%c",B,ch);
  64.  
  65.        printf("%s---%i----%i\n",B,strlen(B),count);
  66.      }
  67.      ch=getc(stdin);
  68.      count=count+1;
  69.    }
  70.  
  71.   /* copy results to return value */
  72.   if (S && B)
  73.    strcpy(S, B);
  74.  
  75.  }
  76.  
  77.  
  78.  
  79.